<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/4/3
 * Time: 19:09
 */

namespace iBrand\Shop\Server\Controllers\V2;

use iBrand\Common\Controllers\Controller;
use iBrand\Component\Discount\Repositories\DiscountRepository;
use iBrand\Shop\Server\Resources\DiscountsResource;

class DiscountController extends Controller
{
	protected $discountRepository;

	public function __construct(DiscountRepository $discountRepository)
	{
		$this->discountRepository = $discountRepository;
	}

	public function getDiscountByShopID()
	{
		$shop_id = request('shop_id');

		$discounts = $this->discountRepository->getDiscountByType(0, 'shop', 'all');

		$discount = $discounts->filter(function ($discount) use ($shop_id) {
			$rule = $discount->rules->filter(function ($rule) {
				return $rule->getShops();
			})->first();

			if ($rule) {
				$shops = $rule->getShops();

				return in_array($shop_id, explode(',', $shops));
			} else {
				return true;
			}
		});

		return $this->collection($discount, DiscountsResource::class);
	}
}